package bb.lanxing.activity.sport;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;

import java.util.AbstractCollection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.adapter.BaseListAdapter;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.Log;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;

public class BDOfflineManageActivity extends BaseActivity implements MKOfflineMapListener {
    public static final int REQUEST_MAP_OFFLINE = 1;
    static MKOfflineMap offline;
    private ListView cityListView;
    private TextView noneData;
    private BDOfflineCityAdapter offlineCityAdapter;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.offline_manage);
        setupActionBar(true, -1, true);
        setTitle("百度离线地图管理");
        this.cityListView = (ListView) findViewById(R.id.listView);
        this.noneData = (TextView) findViewById(R.id.map_offline_none_data);
        MKOfflineMap mKOfflineMap = new MKOfflineMap();
        offline = mKOfflineMap;
        mKOfflineMap.init(this);
        showList();
    }

    private void showList() {
        List allUpdateInfo = offline.getAllUpdateInfo();
        if (allUpdateInfo == null) {
            allUpdateInfo = new LinkedList();
        }
        BDOfflineCityAdapter bDOfflineCityAdapter = new BDOfflineCityAdapter(this, allUpdateInfo);
        this.offlineCityAdapter = bDOfflineCityAdapter;
        bDOfflineCityAdapter.notifyDataSetChanged();
        this.cityListView.setAdapter((ListAdapter) this.offlineCityAdapter);
        this.cityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
                BDOfflineManageActivity bDOfflineManageActivity = BDOfflineManageActivity.this;
                bDOfflineManageActivity.registerForContextMenu(bDOfflineManageActivity.cityListView);
                adapterView.showContextMenuForChild(view);
                BDOfflineManageActivity bDOfflineManageActivity2 = BDOfflineManageActivity.this;
                bDOfflineManageActivity2.unregisterForContextMenu(bDOfflineManageActivity2.cityListView);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        offline.init(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_map_offline_bd_manage, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem menuItem) {
        if (menuItem.getItemId() == R.id.map_offline_menu_list) {
            startActivityForResult(new Intent(this, BDOfflineProvincesActivity.class), 1);
            return true;
        }
        return super.onOptionsItemSelected(menuItem);
    }

    @Override
    public void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        if (i2 == -1 && i == 1) {
            AbstractCollection allUpdateInfo = offline.getAllUpdateInfo();
            if (allUpdateInfo == null) {
                allUpdateInfo = new LinkedList();
            }
            this.offlineCityAdapter.update((List<MKOLUpdateElement>) allUpdateInfo, true);
        }
    }

    @Override
    public void onBackPressed() {
        if (hasDownloaded()) {
            new AlertDialog.Builder(this).setTitle(R.string.dialog_prompt).setMessage(R.string.map_dialog_exit_to_pause).setPositiveButton(R.string.exit, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    BDOfflineManageActivity.super.onBackPressed();
                }
            }).setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) null).show();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onHomeBack() {
        if (hasDownloaded()) {
            new AlertDialog.Builder(this).setTitle(R.string.dialog_prompt).setMessage(R.string.map_dialog_exit_to_pause).setPositiveButton(R.string.exit, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    BDOfflineManageActivity.super.onBackPressed();
                }
            }).setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) null).show();
            return true;
        }
        return super.onHomeBack();
    }

    @Override
    public void onDestroy() {
        pauseAll();
        try {
            offline.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    public boolean hasDownloaded() {
        for (int i = 0; i < this.offlineCityAdapter.getCount(); i++) {
            MKOLUpdateElement item = this.offlineCityAdapter.getItem(i);
            if (item.status == 1 || item.status == 2) {
                return true;
            }
        }
        return false;
    }

    private void pauseAll() {
        for (int i = 0; i < this.offlineCityAdapter.getCount(); i++) {
            MKOLUpdateElement item = this.offlineCityAdapter.getItem(i);
            if (item.status == 1 || item.status == 2) {
                offline.pause(item.cityID);
            }
        }
    }

    @Override
    public void onGetOfflineMapState(int i, int i2) {
        MKOLUpdateElement updateInfo;
        if (i != 0 || (updateInfo = offline.getUpdateInfo(i2)) == null) {
            return;
        }
        this.offlineCityAdapter.update(updateInfo);
        if ((updateInfo.status != 1 && updateInfo.status != 10) || updateInfo.ratio != 100) {
            return;
        }
        Observable.just(updateInfo.cityID).delay(100L, TimeUnit.MILLISECONDS).flatMap(new Func1<Integer, Observable<MKOLUpdateElement>>() {
            @Override
            public Observable<MKOLUpdateElement> call(Integer num) {
                return Observable.just(BDOfflineManageActivity.offline.getUpdateInfo(num));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<MKOLUpdateElement>() {
            @Override
            public void call(MKOLUpdateElement mKOLUpdateElement) {
                BDOfflineManageActivity.this.offlineCityAdapter.update(mKOLUpdateElement);
            }
        });
    }

    @Override
    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
        MKOLUpdateElement item = this.offlineCityAdapter.getItem(((AdapterView.AdapterContextMenuInfo) contextMenuInfo).position);
        if (item.update && item.status == 4) {
            contextMenu.add(0, 1, 0, getString(R.string.update));
        } else if (item.status == 3) {
            contextMenu.add(0, 2, 0, getString(R.string.map_offline_btn_download));
        }
        if (item.status == 1 || item.status == 2) {
            contextMenu.add(0, 3, 0, getString(R.string.map_offline_btn_pause));
        }
        contextMenu.add(0, 4, 0, getString(R.string.delete));
        super.onCreateContextMenu(contextMenu, view, contextMenuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem menuItem) {
        MKOLUpdateElement item = this.offlineCityAdapter.getItem(((AdapterView.AdapterContextMenuInfo) menuItem.getMenuInfo()).position);
        int itemId = menuItem.getItemId();
        if (itemId == 1 || itemId == 2) {
            offline.start(item.cityID);
            if (item.update && item.status == 4) {
                offline.update(item.cityID);
                this.offlineCityAdapter.update(offline.getUpdateInfo(item.cityID));
            } else {
                offline.start(item.cityID);
                this.offlineCityAdapter.update(offline.getUpdateInfo(item.cityID));
            }
        } else if (itemId != 3) {
            if (itemId == 4) {
                offline.remove(item.cityID);
                this.offlineCityAdapter.remove(item);
            }
        } else if (item.status == 1 || item.status == 2) {
            offline.pause(item.cityID);
            this.offlineCityAdapter.update(offline.getUpdateInfo(item.cityID));
        }
        return super.onContextItemSelected(menuItem);
    }

    public class BDOfflineCityAdapter extends BaseListAdapter<MKOLUpdateElement> {
        private String[] statusTypes;

        private BDOfflineCityAdapter(Context context, List<MKOLUpdateElement> list) {
            super(context, list);
            this.statusTypes = this.mContext.getResources().getStringArray(R.array.map_offline_state);
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            String string;
            if (view == null) {
                view = LayoutInflater.from(this.mContext).inflate(R.layout.city_item, viewGroup, false);
                viewHolder = new ViewHolder(view);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }
            MKOLUpdateElement item = getItem(i);
            viewHolder.name.setText(item.cityName);
            viewHolder.size.setText(CommonUtil.getSizeString(item.serversize));
            Log.i("download", "update=" + item.update + " status=" + item.status);
            if (item.status != 1) {
                if (item.status != 2) {
                    if (item.status != 4 && item.status != 10) {
                        if (item.status == 3) {
                            if (viewHolder.state.getVisibility() != View.VISIBLE) {
                                viewHolder.state.setVisibility(View.VISIBLE);
                            }
                            string = this.statusTypes[3];
                        } else {
                            if (viewHolder.state.getVisibility() == View.VISIBLE) {
                                viewHolder.state.setVisibility(View.GONE);
                            }
                            string = "";
                        }
                    } else {
                        if (viewHolder.state.getVisibility() != View.VISIBLE) {
                            viewHolder.state.setVisibility(View.VISIBLE);
                        }
                        if (item.update) {
                            string = this.mContext.getString(R.string.map_offline_city_has_update);
                        } else {
                            if (viewHolder.state.getVisibility() == View.VISIBLE) {
                                viewHolder.state.setVisibility(View.GONE);
                            }
                            string = "";
                        }
                    }
                } else {
                    if (viewHolder.state.getVisibility() != View.VISIBLE) {
                        viewHolder.state.setVisibility(View.VISIBLE);
                    }
                    string = this.statusTypes[1];
                }
            } else {
                if (viewHolder.state.getVisibility() != View.VISIBLE) {
                    viewHolder.state.setVisibility(View.VISIBLE);
                }
                string = this.statusTypes[0] + " " + item.ratio + " %";
            }
            viewHolder.state.setText(string);
            return view;
        }

        public void update(MKOLUpdateElement mKOLUpdateElement) {
            for (int i = 0; i < this.dataSet.size(); i++) {
                if (((MKOLUpdateElement) this.dataSet.get(i)).cityID == mKOLUpdateElement.cityID) {
                    this.dataSet.set(i, mKOLUpdateElement);
                    notifyDataSetChanged();
                    return;
                }
            }
        }

        public void remove(MKOLUpdateElement mKOLUpdateElement) {
            int i = 0;
            while (i < this.dataSet.size() && ((MKOLUpdateElement) this.dataSet.get(i)).cityID != mKOLUpdateElement.cityID) {
                i++;
            }
            if (i < 0 || i >= this.dataSet.size()) {
                return;
            }
            this.dataSet.remove(i);
            notifyDataSetChanged();
        }

        @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
            if (this.dataSet.isEmpty()) {
                BDOfflineManageActivity.this.cityListView.setVisibility(View.GONE);
                BDOfflineManageActivity.this.noneData.setVisibility(View.VISIBLE);
                return;
            }
            BDOfflineManageActivity.this.noneData.setVisibility(View.GONE);
            BDOfflineManageActivity.this.cityListView.setVisibility(View.VISIBLE);
        }

        class ViewHolder {
            private TextView name;
            private TextView size;
            private TextView state;

            private void bindView(View view) {
                this.name = (TextView) view.findViewById(R.id.item);
                this.size = (TextView) view.findViewById(R.id.size);
                this.state = (TextView) view.findViewById(R.id.state);
            }

            public ViewHolder(View view) {
                bindView(view);
            }
        }
    }
}